﻿Imports System.Windows.Media.Imaging

Partial Public Class SilverCard
  Inherits UserControl

  Private myCard As Engine.Card
  ''' <summary>
  ''' the card object that this UI element represents.
  ''' </summary>
  Public ReadOnly Property Card() As Engine.Card
    Get
      Return myCard
    End Get
  End Property

  Public Event Click(ByVal sender As Object, ByVal e As EventArgs)

  ''' <summary>
  ''' constructor
  ''' </summary>
  ''' <param name="card">card object to show</param>
  Public Sub New(ByVal card As Engine.Card)
    InitializeComponent()

    'keep card
    myCard = card

    'add handler for turned event
    AddHandler myCard.Turned, AddressOf myImage_Turned
    'and taken event
    AddHandler myCard.TakenChanged, AddressOf myImage_Taken

    'set image source to card uri
    myImage.Source = New BitmapImage(myCard.ImageUri)

    'facing the right side
    setCardFace()
  End Sub

  ''' <summary>
  ''' default constructor
  ''' </summary>
  Public Sub New()
    InitializeComponent()
  End Sub

  Private Sub myImage_Turned(ByVal sender As Object, ByVal e As Engine.CardTurnedEventArgs)
    'invoke on the right thread (can be called from another thread)
    myImage.Dispatcher.BeginInvoke(AddressOf setCardFace)
  End Sub

  Private Sub myImage_Taken(ByVal sender As Object, ByVal e As EventArgs)
    myImage.Dispatcher.BeginInvoke(AddressOf hideCard)
  End Sub

  ''' <summary>
  ''' make the card face the right side
  ''' </summary>
  Private Sub setCardFace()
    If myCard.Facing = Engine.Card.Face.Up Then
      myImage.Visibility = Windows.Visibility.Visible
      ImageDownFace.Visibility = Windows.Visibility.Collapsed
      BorderEllipse.Visibility = Windows.Visibility.Collapsed
    Else
      myImage.Visibility = Windows.Visibility.Collapsed
      ImageDownFace.Visibility = Windows.Visibility.Visible
      BorderEllipse.Visibility = Windows.Visibility.Visible
    End If
  End Sub

  Private Sub hideCard()
    If myCard.Taken Then
      EmptyBorder.Visibility = Windows.Visibility.Visible
      GridCard.Visibility = Windows.Visibility.Collapsed
    End If
  End Sub

  Private Sub BorderCard_MouseLeftButtonUp(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
    RaiseEvent Click(Me, New EventArgs)
  End Sub
End Class
